package com.prp.gwt.client.widgets.admin;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.prp.gwt.client.IListener;
import com.prp.gwt.client.admin.AdminListener;
import com.prp.gwt.client.vo.UserList;
import com.prp.gwt.client.widgets.ConfirmDialog;
import com.prp.gwt.client.widgets.IWidget;

public class InactivatedUserList extends VerticalPanel implements IWidget {
	private static InactivatedUserList instance;
	private FlexTable table = new FlexTable();
	private HTML message = new HTML();

	public static InactivatedUserList getInstance() {
		if (instance == null)
			instance = new InactivatedUserList();
		return instance;
	}

	private InactivatedUserList() {
		HorizontalPanel panel = new HorizontalPanel();
		panel.setSpacing(10);
		panel.add(new HTML("未激活帐户列表:"));
		Button refresh = new Button("刷新");
		panel.add(refresh);
		panel.add(message);
		add(panel);
		table.setCellSpacing(5);
		add(table);

		refresh.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				AdminListener.getInstance().getInactivatedUserList();
				message.setText("正在刷新");
			}
		});
	}

	public void update(final UserList userList) {
		int n = table.getRowCount();
		for (int i = n - 1; i >= 0; i--)
			table.removeRow(i);
		int row = 0;
		table.setHTML(row, 0, "邮箱");
		table.setHTML(row++, 1, "用户名");
		for (int i = 0; i < userList.size(); i++, row++) {
			table.setHTML(row, 0, userList.get(i).getEmail());
			table.setHTML(row, 1, userList.get(i).getUsername());
			Button activate = new Button("激活帐户");
			Button delete = new Button("删除帐户");
			table.setWidget(row, 2, activate);
			table.setWidget(row, 3, delete);
			final int k = i;
			activate.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					AdminListener.getInstance().activateUser(
							userList.get(k).getEmail());
				}
			});
			delete.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					ConfirmDialog.getInstance().setCallFunction(
							InactivatedUserList.this,
							userList.get(k).getEmail());
					ConfirmDialog.getInstance().show(
							"确认删除?",
							"确认删除帐户" + userList.get(k).getEmail() + "吗?<br/>"
									+ "删除后此帐户的所有的信息将无法找回!");
				}
			});
		}
		message.setText("");
	}

	public void showMessage(String text) {
		message.setText(text);
	}

	@Override
	public void callFunction(Object arg) {
		AdminListener.getInstance().deleteUser((String) arg);
	}

	@Override
	public void setListener(IListener listener) {
		// do nothing
	}

}
